/*
 * Copyright (c) 2018-2999 北京小象智慧信息科技有限公司 All rights reserved.
 *
 * https://www.xiaoxiangai.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.common.config.AliConfig;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yami.shop.bean.model.AttachFile;
import com.yami.shop.common.bean.Qiniu;
import com.yami.shop.common.util.Json;
import com.yami.shop.dao.AttachFileMapper;
import com.yami.shop.service.AttachFileService;
import cn.hutool.core.io.FileUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * Created by lgh on 2018/07/27.
 */
@Service
public class AttachFileServiceImpl extends ServiceImpl<AttachFileMapper, AttachFile> implements AttachFileService {

    @Autowired
    private AttachFileMapper attachFileMapper;

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private BucketManager bucketManager;
	@Autowired
	private Qiniu qiniu;

    @Autowired
    private Auth auth;

    public final static String NORM_MONTH_PATTERN = "yyyy/MM/";


	public static final String[] DEFAULT_ALLOWED_EXTENSION = {
			// 图片
			"bmp", "gif", "jpg", "jpeg", "png",
			// word excel powerpoint
			"doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
			// 压缩文件
			"rar", "zip", "gz", "bz2",
			// 视频格式
			"mp4", "avi", "rmvb",
			// pdf
			"pdf" };

	@Override
	public String upload(MultipartFile file) throws IOException {
		try
		{
			String extName = FileUtil.extName(file.getOriginalFilename());
			String fileName = DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;

			AttachFile attachFile = new AttachFile();
			attachFile.setFilePath(fileName);
			attachFile.setFileSize(file.getBytes().length);
			attachFile.setFileType(extName);
			attachFile.setUploadTime(new Date());
			attachFileMapper.insert(attachFile);

			return AliConfig.getImgPrefix()+upload(file, DEFAULT_ALLOWED_EXTENSION);
		}
		catch (Exception e)
		{
			throw new IOException(e.getMessage(), e);
		}
	}


	public static final String datePath()
	{
		Date now = new Date();
		return DateFormatUtils.format(now, "yyyy/MM/dd");
	}

	public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

	public static final String dateTimeNow()
	{
		return dateTimeNow(YYYYMMDDHHMMSS);
	}

	public static final String dateTimeNow(final String format)
	{
		return parseDateToStr(format, new Date());
	}

	public static final String parseDateToStr(final String format, final Date date)
	{
		return new SimpleDateFormat(format).format(date);
	}

	public static final String upload( MultipartFile file, String[] allowedExtension)
			throws  Exception
	{
		String fileName = file.getOriginalFilename();
		if("blob".equalsIgnoreCase(fileName)){
			fileName =datePath()+"/"+ fileName+dateTimeNow()+".jpg";
		}else {
			fileName = datePath() + "/" + fileName;
		}
		uploadToOss(file.getInputStream(), fileName);
		return fileName;
	}

	public static void uploadToOss(InputStream inputStream, String pathFileName)throws Exception {
		try {

			String endpoint = AliConfig.getEndpoint();
			// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
			String accessKeyId = AliConfig.getAccessKeyId();
			String accessKeySecret = AliConfig.getAccessKeySecret();
			String bucketName = AliConfig.getBucket();
			// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
			String objectName = pathFileName;
			// 创建OSSClient实例。
			OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
			// 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
			ossClient.putObject(bucketName, objectName, inputStream);
			// 关闭OSSClient。
			ossClient.shutdown();
		} catch (Exception e) {
			throw new Exception("文件上传失败");
		}
	}

	@Override
	public void deleteFile(String fileName){
		attachFileMapper.delete(new LambdaQueryWrapper<AttachFile>().eq(AttachFile::getFilePath,fileName));
		try {
			bucketManager.delete(qiniu.getBucket(), fileName);
		} catch (QiniuException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String ScanUpload(byte[] bytes, String originalName,String cid) throws IOException {
		String extName = FileUtil.extName(originalName);
		String fileName =DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;


		AttachFile attachFile = new AttachFile();
		attachFile.setFilePath(fileName);
		attachFile.setFileSize(bytes.length);
		attachFile.setFileType(extName);
		attachFile.setUploadTime(new Date());
		attachFile.setCid(cid);
		attachFileMapper.insert(attachFile);

		String upToken = auth.uploadToken(qiniu.getBucket(),fileName);
		Response response = uploadManager.put(bytes, fileName, upToken);
		Json.parseObject(response.bodyString(),  DefaultPutRet.class);
		return fileName;
	}

	@Override
	public String getLatestPicByCid(String cid) {
		String photoUrl = attachFileMapper.getLatestPicByCid(cid);
		return photoUrl;
	}


}
